import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useGameStore } from '../store/gameStore';
import { Star, Trophy, Clock, Target, Coins, ArrowRight, RotateCcw, Home, Heart, Award, TrendingUp } from 'lucide-react';

interface GameResultProps {
  isVisible: boolean;
  onClose: () => void;
  levelId: string;
  gameResult: {
    completed: boolean;
    score: number;
    time: number;
    healthRemaining: number;
    maxHealth: number;
    unitsUsed: number;
    skillsUsed: number;
    moodCollected: number;
    waveReached: number;
    maxWave: number;
  };
}

interface GameStats {
  completionTime: number;
  enemiesKilled: number;
  chessSpiritSpent: number;
  unitsUsed: string[];
  perfectDefense: boolean;
  fastCompletion: boolean;
  economicalVictory: boolean;
}

export default function GameResult({ isVisible, onClose, levelId, gameResult }: GameResultProps) {
  const navigate = useNavigate();
  const { gameState, currentLevel, updateProgress, completeLevel, getLevelProgress } = useGameStore();
  const [stats, setStats] = useState<GameStats | null>(null);
  const [stars, setStars] = useState(0);
  const [showAnimation, setShowAnimation] = useState(false);
  const [levelResult, setLevelResult] = useState<any>(null);
  const [previousProgress, setPreviousProgress] = useState<any>(null);

  // 计算游戏统计和星级
  useEffect(() => {
    if (isVisible && gameResult.completed) {
      // 获取之前的进度
      const prevProgress = getLevelProgress(levelId);
      setPreviousProgress(prevProgress);
      
      // 完成关卡并保存进度
      const result = completeLevel(levelId, gameResult);
      setLevelResult(result);
      
      if (gameState.gameStatus === 'victory' && currentLevel) {
        const completionTime = Math.floor((Date.now() - gameState.lastUpdateTime) / 1000);
        const enemiesKilled = 50; // 这里应该从游戏状态中获取实际击杀数
        const chessSpiritSpent = currentLevel.initialChessSpirit - gameState.chessSpirit;
        const unitsUsed = gameState.units.map(unit => unit.type);
        
        // 计算成就条件
        const perfectDefense = gameState.playerHealth === currentLevel.playerHealth;
        const fastCompletion = completionTime < 300; // 5分钟内完成
        const economicalVictory = chessSpiritSpent < currentLevel.initialChessSpirit * 0.7;
        
        const gameStats: GameStats = {
          completionTime,
          enemiesKilled,
          chessSpiritSpent,
          unitsUsed,
          perfectDefense,
          fastCompletion,
          economicalVictory
        };
        
        setStats(gameStats);
        
        // 计算星级评价
        let starCount = 1; // 基础1星（完成关卡）
        if (perfectDefense) starCount++; // 完美防御+1星
        if (fastCompletion || economicalVictory) starCount++; // 快速完成或经济胜利+1星
        
        setStars(Math.min(starCount, 3));
        
        // 更新玩家进度
          const score = calculateScore(gameStats);
          // 注意：进度更新已通过completeLevel方法处理
          // updateProgress(currentLevel.id, {
          //   bestScore: score,
          //   stars: starCount,
          //   unlocked: true,
          //   statistics: {
          //     completionTime,
          //     unitsUsed,
          //     enemiesKilled,
          //     chessSpiritSpent
          //   }
          // });
        
        // 延迟显示动画
        setTimeout(() => setShowAnimation(true), 500);
      }
    }
  }, [isVisible, gameResult.completed, levelId, completeLevel, getLevelProgress, gameState, currentLevel, updateProgress]);

  // 计算分数
  const calculateScore = (stats: GameStats): number => {
    let score = 1000; // 基础分数
    
    // 时间奖励
    if (stats.fastCompletion) score += 500;
    else if (stats.completionTime < 600) score += 300;
    
    // 防御奖励
    if (stats.perfectDefense) score += 500;
    
    // 经济奖励
    if (stats.economicalVictory) score += 300;
    
    // 击杀奖励
    score += stats.enemiesKilled * 10;
    
    return score;
  };

  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const getUnitName = (type: string): string => {
    const names: Record<string, string> = {
      soldier: '锐士',
      cannon: '神射',
      horse: '骠骑',
      chariot: '战车',
      advisor: '谋士',
      minister: '丞相',
      general: '元帅'
    };
    return names[type] || type;
  };

  if (!isVisible) {
    return null;
  }

  const starsToShow = levelResult?.rating?.stars || stars || 0;
  const totalScore = gameResult.score;
  const isNewRecord = levelResult && (!previousProgress || gameResult.score > previousProgress.bestScore);

  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50">
      <div className="bg-gradient-to-br from-amber-50 to-amber-100 rounded-2xl p-8 max-w-2xl w-full mx-4 border-4 border-amber-600 shadow-2xl">
        {/* 标题 */}
        <div className="text-center mb-6">
          <div className="flex items-center justify-center mb-4">
            <Trophy className="w-12 h-12 text-amber-600 mr-3" />
            <h2 className="text-4xl font-bold text-amber-900">
              {gameResult.completed ? '胜利！' : '挑战失败'}
            </h2>
          </div>
          <p className="text-xl text-amber-800">{currentLevel?.name || `关卡 ${levelId}`}</p>
          
          {/* 新记录提示 */}
          {isNewRecord && (
            <div className="flex items-center justify-center space-x-2 text-green-600 bg-green-50 rounded-lg px-3 py-1 inline-flex mt-2">
              <Award className="w-4 h-4" />
              <span className="text-sm font-semibold">新记录！</span>
            </div>
          )}
        </div>

        {/* 星级评价 */}
        <div className="flex justify-center mb-8">
          <div className="flex space-x-2">
            {[1, 2, 3].map((star) => (
              <Star
                key={star}
                className={`w-12 h-12 transition-all duration-500 ${
                  showAnimation && star <= starsToShow
                    ? 'text-yellow-400 fill-yellow-400 scale-110 animate-pulse'
                    : 'text-gray-300'
                }`}
                style={{
                  animationDelay: showAnimation ? `${star * 200}ms` : '0ms'
                }}
              />
            ))}
          </div>
          
          <div className="text-lg text-gray-600 mt-4">
            {starsToShow === 3 && '完美通关！'}
            {starsToShow === 2 && '表现优秀！'}
            {starsToShow === 1 && '成功通关！'}
            {starsToShow === 0 && '继续努力！'}
          </div>
        </div>

        {/* 统计数据 */}
        <div className="grid grid-cols-2 gap-6 mb-8">
          <div className="bg-white/50 rounded-lg p-4 border border-amber-300">
            <div className="flex items-center mb-2">
              <Trophy className="w-6 h-6 text-amber-700 mr-2" />
              <span className="font-semibold text-amber-900">总分</span>
            </div>
            <p className="text-2xl font-bold text-amber-800">
              {totalScore.toLocaleString()}
            </p>
            {previousProgress && gameResult.score > previousProgress.bestScore && (
              <p className="text-sm text-green-600 mt-1">+{(gameResult.score - previousProgress.bestScore).toLocaleString()}</p>
            )}
          </div>

          <div className="bg-white/50 rounded-lg p-4 border border-amber-300">
            <div className="flex items-center mb-2">
              <Clock className="w-6 h-6 text-amber-700 mr-2" />
              <span className="font-semibold text-amber-900">完成时间</span>
            </div>
            <p className="text-2xl font-bold text-amber-800">
              {Math.floor(gameResult.time / 60000)}:{String(Math.floor((gameResult.time % 60000) / 1000)).padStart(2, '0')}
            </p>
            {previousProgress && gameResult.time < previousProgress.bestTime && (
              <p className="text-sm text-green-600 mt-1">更快了！</p>
            )}
          </div>

          <div className="bg-white/50 rounded-lg p-4 border border-amber-300">
            <div className="flex items-center mb-2">
              <Heart className="w-6 h-6 text-amber-700 mr-2" />
              <span className="font-semibold text-amber-900">剩余生命</span>
            </div>
            <p className="text-2xl font-bold text-amber-800">
              {Math.floor((gameResult.healthRemaining / gameResult.maxHealth) * 100)}%
            </p>
          </div>

          <div className="bg-white/50 rounded-lg p-4 border border-amber-300">
            <div className="flex items-center mb-2">
              <Target className="w-6 h-6 text-amber-700 mr-2" />
              <span className="font-semibold text-amber-900">意境收集</span>
            </div>
            <p className="text-2xl font-bold text-amber-800">
              {gameResult.moodCollected}
            </p>
          </div>
        </div>

        {/* 详细数据 */}
        <div className="bg-white/30 rounded-lg p-4 mb-8">
          <h3 className="text-lg font-semibold text-amber-900 mb-3">详细数据</h3>
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div className="flex justify-between">
              <span className="text-amber-700">使用单位:</span>
              <span className="font-semibold text-amber-900">{gameResult.unitsUsed}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-amber-700">使用技能:</span>
              <span className="font-semibold text-amber-900">{gameResult.skillsUsed}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-amber-700">到达波次:</span>
              <span className="font-semibold text-amber-900">{gameResult.waveReached}/{gameResult.maxWave}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-amber-700">意境收集:</span>
              <span className="font-semibold text-amber-900">{gameResult.moodCollected}</span>
            </div>
          </div>
          
          {/* 评分详情 */}
          {levelResult?.rating?.breakdown && (
            <div className="mt-4 pt-4 border-t border-amber-300">
              <h4 className="text-sm font-semibold text-amber-800 mb-2">评分详情</h4>
              <div className="space-y-1 text-xs">
                {Object.entries(levelResult.rating.breakdown).map(([key, value]: [string, any]) => {
                  const labels: Record<string, string> = {
                    completion: '完成奖励',
                    time: '时间奖励',
                    health: '生命奖励',
                    efficiency: '效率奖励',
                    mood: '意境奖励'
                  };
                  return (
                    <div key={key} className="flex justify-between">
                      <span className="text-amber-700">{labels[key] || key}:</span>
                      <span className="font-semibold text-amber-900">+{value}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* 使用的单位 */}
        {stats && (
          <div className="mb-8">
            <h3 className="text-lg font-semibold text-amber-900 mb-3">使用单位</h3>
            <div className="flex flex-wrap gap-2">
              {Array.from(new Set(stats.unitsUsed)).map((unitType, index) => (
                <span
                  key={index}
                  className="bg-amber-200 text-amber-800 px-3 py-1 rounded-full text-sm font-medium border border-amber-400"
                >
                  {getUnitName(unitType)}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* 按钮 */}
        <div className="flex justify-center space-x-4">
          <button
            onClick={() => {
              useGameStore.getState().restartGame();
              onClose();
            }}
            className="flex items-center px-6 py-3 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors font-semibold"
          >
            <RotateCcw className="w-5 h-5 mr-2" />
            重新挑战
          </button>
          
          <button
            onClick={() => {
              navigate('/levels');
              onClose();
            }}
            className="flex items-center px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors font-semibold"
          >
            <Home className="w-5 h-5 mr-2" />
            返回关卡
          </button>
          
          <button
            onClick={() => {
              // 这里可以添加下一关的逻辑
              navigate('/levels');
              onClose();
            }}
            className="flex items-center px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-semibold"
          >
            下一关
            <ArrowRight className="w-5 h-5 ml-2" />
          </button>
        </div>
      </div>
    </div>
  );
}